#!/bin/bash

# bash <(curl -s -L https://gitee.com/securitypass/auto-scirpt/raw/master/docker/openresty/openresty_install.sh)

# 1. 检查基础命令
for cmd in systemctl; do
    if ! command -v $cmd &>/dev/null; then
        echo "缺少 $cmd 命令，请确认系统环境，只适用于 CentOS/RHEL/AlmaLinux/Rocky等版本。"
        exit 1
    fi
done

if ! command -v yum &>/dev/null && ! command -v dnf &>/dev/null; then
    echo "缺少 yum 或 dnf 命令，请确认系统环境。"
    exit 1
fi

# 2. 检查并安装 Docker
if ! command -v docker &>/dev/null; then
    echo "未检测到 Docker，正在安装..."
    if command -v dnf &>/dev/null; then
        sudo dnf install -y docker
    else
        sudo yum install -y docker
    fi
    sudo systemctl enable docker
    sudo systemctl start docker
fi

# 3. 拉取并运行 openresty 镜像
IMAGE_NAME="1.abclist.eu.org/openresty/openresty:1.27.1.2-4-alpine-fat-amd64"
docker pull $IMAGE_NAME

# 4. 让用户输入本地配置文件目录
read -p "请输入本地配置文件目录路径: " CONF_DIR
if [ ! -d "$CONF_DIR" ]; then
    echo "目录不存在，正在创建..."
    mkdir -p "$CONF_DIR"
fi
if [ -d "$CONF_DIR/conf.d" ]; then
    echo "检测到旧的 $CONF_DIR/conf.d，正在删除..."
    rm -rf "$CONF_DIR/conf.d"
fi
mkdir -p "$CONF_DIR/conf.d"
chmod -R 777 "$CONF_DIR/conf.d"

# 5. 下载配置文件到指定目录
for file in antibot.conf blacklist.conf opac.conf opac-81.conf referer_check.conf trusted_ip.conf ua_blacklist.conf waf.conf blacklist.txt; do
    curl -fsSL -o "$CONF_DIR/conf.d/$file" "https://gitee.com/securitypass/auto-scirpt/raw/master/docker/openresty/$file"
    curl -fsSL -o "$CONF_DIR/nginx.conf" "https://gitee.com/securitypass/auto-scirpt/raw/master/docker/openresty/nginx.conf"
done

# 6. 让用户输入端口号
read -p "请输入要映射的主机第一个端口号（如80）: " HOST_PORT_1

read -p "请输入要映射的主机第二个端口号（如8888）: " HOST_PORT_2

# 7. 自动判断并清理已存在的 opac 容器
if docker ps -a --format '{{.Names}}' | grep -wq opac; then
    docker stop openresty
    docker rm openresty
fi

# 运行容器并挂载配置
docker run -d --name openresty \
    -p 443:443 \
    -p $HOST_PORT_1:80 \
    -p $HOST_PORT_2:8080 \
    -v /etc/localtime:/etc/localtime:ro \
    -v /etc/timezone:/etc/timezone:ro \
    -e TZ=Asia/Shanghai \
    -v "$CONF_DIR/nginx.conf:/etc/nginx/nginx.conf" \
    -v "$CONF_DIR/conf.d:/etc/nginx/conf.d" \
    -v "$CONF_DIR/html:/usr/local/openresty/nginx/html" \
    -v "$CONF_DIR/logs:/usr/local/openresty/nginx/logs" \
    $IMAGE_NAME